﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Marketplace;
using Microsoft.Phone.Tasks;

namespace SkyReader
{
    public partial class Bookshelf : PhoneApplicationPage
    {

        private bool CheckIsTrial()
        {
#if DEBUG
                MessageBoxResult result = MessageBox.Show("CLICK OK TO SIMULATE FULL LICENSE","BUY NOW!",MessageBoxButton.OKCancel);
                
                if (result == MessageBoxResult.OK)
                {
                return false;
                }
                else
                {
                return true;
                }
#else
            LicenseInformation licenseInfo = new LicenseInformation();
            return licenseInfo.IsTrial();
#endif
        }


        public Bookshelf()
        {
            InitializeComponent();
            Deployment.Current.Dispatcher.BeginInvoke(BindBookList);
        }

        private List<Book> bookList; 
        private void BindBookList()
        {
            bookList = new List<Book>();
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

            foreach (var setting in settings)
            {
                if (setting.Value is Book)
                {
                    Book book = setting.Value as Book;
                    bookList.Add(book);
                }
            }

            // sort book list according to title of the book
            var sortBooks = from sBook in bookList
                            orderby sBook.DateCreated descending
                            select sBook;
            List<Book> sortBookList = sortBooks.ToList<Book>();
            lstBook.ItemsSource = sortBookList;


            this.LoadPanel.Visibility = System.Windows.Visibility.Collapsed;
            this.lstBook.Visibility = System.Windows.Visibility.Visible;


            if (bookList.Count == 0)
            {
                this.lblInformation.Text = "1. Upload books (plain text file) to SkyDrive using your computer.\r\n \r\n2. Click the icon to download the books from Skydrive. \r\n \r\n3. Convert encoding of the text to UTF 8 if the encoding is in Chinese encoding or other encodings that are supported by Windows Phone 7 before update the text file to SkyDrive.";
                this.lblInformation.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                this.lblInformation.Visibility = System.Windows.Visibility.Collapsed;
            }

            if (this.CheckIsTrial() && bookList.Count >2)
            {
                this.lstBook.Visibility = System.Windows.Visibility.Collapsed;
                this.LicensePanel.Visibility = System.Windows.Visibility.Visible;
                return;
            }



        }
        private void btnBuyNow_Click(object sender, EventArgs e)
        {
            MarketplaceDetailTask detailTask = new MarketplaceDetailTask();
            detailTask.Show();

            this.lstBook.Visibility = System.Windows.Visibility.Visible;
            this.LicensePanel.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.lstBook.Visibility = System.Windows.Visibility.Visible;
            this.LicensePanel.Visibility = System.Windows.Visibility.Collapsed;
        }
        private void DownloadButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Download.xaml", UriKind.Relative));
        }

        private void btnDownloadFromLocal_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/LocalBooks.xaml", UriKind.Relative));
        }


        private void DeleteMenuItem_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("This Book will be deleted from your bookshelf.", "Delete book?", MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                string bookId= ((FrameworkElement)sender).Tag.ToString();
                IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
                Book book = settings[bookId] as Book;

                IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication();
                if (isoFile.FileExists(book.FileName))
                {
                    isoFile.DeleteFile(book.FileName);
                }

                settings.Remove(bookId);
                settings.Save();

                // rebind book list
                BindBookList();
            }
        }

        private void OpenMenuItem_Click(object sender, RoutedEventArgs e)
        {
            FrameworkElement item = sender as FrameworkElement;
            string fileName = item.Tag.ToString();
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            settings["VARIABLE_CURRENTFILENAME"] = fileName;

            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void ButtonOpenBook_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            string fileName = button.Tag.ToString();
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            settings["VARIABLE_CURRENTFILENAME"] = fileName;

            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }
        

        private void purchaseButton_Click(object sender, EventArgs e)
        {
            MarketplaceDetailTask detailTask = new MarketplaceDetailTask();
            detailTask.Show();

            this.lstBook.Visibility = System.Windows.Visibility.Visible;
            this.LicensePanel.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!this.CheckIsTrial())
            {
                if (this.ApplicationBar.Buttons.Count == 3)
                {
                    object btnPurchase = this.ApplicationBar.Buttons[2];
                    this.ApplicationBar.Buttons.Remove(btnPurchase);
                }
            }
        }
    }
}